package epam.concurrency.lab2.task5;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Bank with thread-safe transactions
 * @author Iurii Miedviediev
 * @version 1.0 Build 17.08.2014
 */
public class Bank {

    List<Account> accounts = new ArrayList<>();
    Lock bankLock = new ReentrantLock();

    /**
     * Make a transaction
     * @param fromIndex index of Account to check out money
     * @param toIndex index of Account to check in money
     * @param amount money ($)
     */
    public void transfer(int fromIndex, int toIndex, int amount) {
        Account from = accounts.get(fromIndex);
        Account to = accounts.get(toIndex);

        if (from.withdraw(amount)) {
            to.deposit(amount);
        }
    }

    /**
     * Get balance from all the accounts from the bank
     * Lock guarantees that no transactions could take place while
     * total balance is computing
     *
     * @return amount of money on all the bank accounts
     */
    public long getTotalBalance() {
        bankLock.lock();
        try {
            long result = 0;
            for(Account a : accounts) {
                result += a.getAmount();
            }
            return result;
        } finally {
            bankLock.unlock();
        }
    }
}
